package com.kandinfo.base.common.util.sftp;

import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.kandinfo.base.common.constant.WebConstants;

public class SFTPChannel {
    
    private static final Logger logger = LoggerFactory.getLogger(SFTPChannel.class);

    Session session = null;
    Channel channel = null;

    public ChannelSftp getChannel() throws JSchException {

        String ftpHost = WebConstants.getProperty(WebConstants.SFTPHOST);
        String port = WebConstants.getProperty(WebConstants.SFTPPORT);
        String ftpUserName = WebConstants.getProperty(WebConstants.SFTPUSERNAME);
        String ftpPassword = WebConstants.getProperty(WebConstants.SFTPPASSWORD);
        int timeout = Integer.valueOf(WebConstants.getProperty(WebConstants.SFTPTIMEOUT)).intValue();

        int ftpPort = SFTPConstants.SFTP_DEFAULT_PORT;
        if (port != null && !port.equals("")) {
            ftpPort = Integer.valueOf(port);
        }
        // 创建JSch对象
        JSch jsch = new JSch();
        // 根据用户名，主机ip，端口获取一个Session对象
        session = jsch.getSession(ftpUserName, ftpHost, ftpPort);
        logger.debug("Session created.");
        if (ftpPassword != null) {
            // 设置密码
            session.setPassword(ftpPassword);
        }
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        // 为Session对象设置properties
        session.setConfig(config);
        // 设置timeout时间
        session.setTimeout(timeout);
        // 通过Session建立链接
        session.connect();
        logger.debug("Session connected.");

        logger.debug("Opening Channel.");
        // 打开SFTP通道
        channel = session.openChannel("sftp");
        // 建立SFTP通道的连接
        channel.connect();
        logger.error("Connected successfully to ftpHost = " + ftpHost + ",as ftpUserName = " + ftpUserName
                + ", returning: " + channel);
        return (ChannelSftp) channel;
    }

    public void closeChannel() throws Exception {
        if (channel != null) {
            channel.disconnect();
        }
        if (session != null) {
            session.disconnect();
        }
    }
}
